<template>
  <view class="setting-container">
    <up-navbar :title="useT('通用设置')" bg-color="#ffffff" :border="false" :safeAreaInsetTop="true" title-color="#333333" placeholder autoBack></up-navbar>
    <!-- 设置菜单列表 -->
    <view class="menu-list">
      <view class="menu-item" @click="changePhone">
        <text class="menu-text">{{ useT('更换邮箱') }}</text>
        <u-icon name="arrow-right" size="34rpx" color="#3B3B3B"></u-icon>
      </view>

      <view class="menu-item" @click="resetPassword">
        <text class="menu-text">{{ useT('重置密码') }}</text>
        <u-icon name="arrow-right" size="34rpx" color="#3B3B3B"></u-icon>
      </view>

      <view class="menu-item" @click="thirdPartyBinding">
        <text class="menu-text">{{ useT('第三方绑定管理') }}</text>
        <u-icon name="arrow-right" size="34rpx" color="#3B3B3B"></u-icon>
      </view>

      <view class="menu-item" @click="languageSwitch">
        <text class="menu-text">{{ useT('语言切换') }}</text>
        <view class="language-info">
          <text class="current-language">{{ currentLanguageName }}</text>
          <u-icon name="arrow-right" size="34rpx" color="#3B3B3B"></u-icon>
        </view>
      </view>

      <view class="menu-item" @click="aboutUs">
        <text class="menu-text">{{ useT('关于我们') }}</text>
        <u-icon name="arrow-right" size="34rpx" color="#3B3B3B"></u-icon>
      </view>

      <view class="menu-item" @click="clearCache">
        <text class="menu-text">{{ useT('清除缓存') }}</text>
        <view class="cache-info">
          <text class="cache-size">{{ cacheSize }}</text>
          <u-icon name="arrow-right" size="34rpx" color="#3B3B3B"></u-icon>
        </view>
      </view>

      <view class="menu-item" @click="checkUpdate">
        <text class="menu-text">{{ useT('版本更新') }}</text>
        <view class="version-info">
          <text class="version-number">{{ versionNumber }}</text>
          <u-icon name="arrow-right" size="34rpx" color="#3B3B3B"></u-icon>
        </view>
      </view>

      <view class="menu-item" @click="deregisterAccount">
        <text class="menu-text">{{ useT('注销账号') }}</text>
        <u-icon name="arrow-right" size="34rpx" color="#3B3B3B"></u-icon>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-section">
      <view class="logout-btn" @click="logout">
        <text class="logout-text">{{ useT('退出登录') }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { useUserStore } from '@/stores/user.js';
import { appUpdate } from '@/utils/appUpdate.js';
import { getCurrentLanguage, useT } from '@/utils/i18n.js';
import { onShow } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';

const userStore = useUserStore();

// 缓存大小和版本号
const cacheSize = ref('85.29MB');
const versionNumber = ref('1.6.5');

// 获取当前语言名称
const currentLanguageName = computed(() => {
  return getCurrentLanguage();
});
onShow(() => {
  versionNumber.value = uni.getAppBaseInfo().appWgtVersion || uni.getAppBaseInfo().appVersion;
});
onMounted(() => {
  // 计算实际缓存大小
  calculateCacheSize();
});

// 计算缓存大小
const calculateCacheSize = () => {
  // #ifdef APP-PLUS
  // APP环境使用plus.cache.calculate
  plus.cache.calculate(function (size) {
    const sizeCache = parseInt(size);
    if (sizeCache === 0) {
      cacheSize.value = '0B';
    } else if (sizeCache < 1024) {
      cacheSize.value = `${sizeCache}B`;
    } else if (sizeCache < 1048576) {
      cacheSize.value = `${(sizeCache / 1024).toFixed(2)}KB`;
    } else if (sizeCache < 1073741824) {
      cacheSize.value = `${(sizeCache / 1048576).toFixed(2)}MB`;
    } else {
      cacheSize.value = `${(sizeCache / 1073741824).toFixed(2)}GB`;
    }
  });
  // #endif

  // #ifndef APP-PLUS
  // 非APP环境使用uni.getStorageInfoSync
  try {
    const storageInfo = uni.getStorageInfoSync();
    const totalSize = storageInfo.currentSize;
    const totalSizeKB = totalSize / 1024;
    const totalSizeMB = totalSizeKB / 1024;

    if (totalSizeMB >= 1) {
      cacheSize.value = `${totalSizeMB.toFixed(2)}MB`;
    } else {
      cacheSize.value = `${totalSizeKB.toFixed(2)}KB`;
    }
  } catch (error) {
    console.error('获取缓存大小失败:', error);
    cacheSize.value = '0KB';
  }
  // #endif
};

// 更换手机号
const changePhone = () => {
  uni.navigateTo({
    url: '/pagesD/setting/changePhone'
  });
};

// 重置登录密码
const resetPassword = () => {
  uni.navigateTo({
    url: '/pages/login/resetPassword'
  });
};

// 第三方绑定管理
const thirdPartyBinding = () => {
  uni.navigateTo({
    url: '/pagesD/setting/thirdPartyBinding'
  });
};

// 语言切换
const languageSwitch = () => {
  uni.navigateTo({
    url: '/pagesD/setting/language'
  });
};

// 关于我们
const aboutUs = () => {
  uni.navigateTo({
    url: '/pagesD/about/about'
  });
};

// 版本更新
const checkUpdate = async () => {
  try {
    // 显示检查更新提示
    uni.showLoading({
      title: useT('检查更新中.')
    });

    // 调用appUpdate进行版本检查
    const hasUpdate = await appUpdate(true); // true表示手动检查更新

    // 隐藏加载提示
    uni.hideLoading();

    if (!hasUpdate) {
      // 如果没有更新，appUpdate内部会显示"已是最新版本"的提示
      uni.showToast({
        title: useT('当前已是最新版本'),
        icon: 'none'
      });
    }
  } catch (error) {
    // 隐藏加载提示
    uni.hideLoading();

    console.error('检查更新失败:', error);
    uni.showToast({
      title: useT('检查更新失败'),
      icon: 'error'
    });
  }
};

// 清除缓存
const clearCache = () => {
  uni.showModal({
    title: useT('清除缓存'),
    content: `${useT('确定要清除')} ${cacheSize.value} ${useT('缓存吗')}？`,
    cancelText: useT('取消'),
    confirmText: useT('确定'),
    success: (res) => {
      if (res.confirm) {
        // #ifdef APP-PLUS
        clearAppCache();
        // #endif

        // #ifndef APP-PLUS
        // 非APP环境，只清除本地存储
        try {
          uni.clearStorageSync();
          cacheSize.value = '0KB';
          uni.showToast({
            title: useT('缓存清除成功'),
            icon: 'success'
          });
        } catch (error) {
          console.error('清除缓存失败:', error);
          uni.showToast({
            title: useT('清除缓存失败'),
            icon: 'error'
          });
        }
        // #endif
      }
    }
  });
};

// APP环境清除缓存
const clearAppCache = () => {
  // #ifdef APP-PLUS
  const os = plus.os.name;
  if (os === 'Android') {
    const main = plus.android.runtimeMainActivity();
    const sdRoot = main.getCacheDir();
    const files = plus.android.invoke(sdRoot, 'listFiles');
    const len = files.length;

    for (let i = 0; i < len; i++) {
      const filePath = `${files[i]}`;
      plus.io.resolveLocalFileSystemURL(
        filePath,
        function (entry) {
          if (entry.isDirectory) {
            entry.removeRecursively(
              function () {
                uni.showToast({
                  title: useT('缓存清除成功'),
                  duration: 2000
                });
                calculateCacheSize(); // 重新计算缓存
              },
              function (error) {
                console.log(error.message);
              }
            );
          } else {
            entry.remove();
          }
        },
        function (error) {
          console.log('文件路径读取失败', error);
        }
      );
    }
  } else {
    // iOS环境
    plus.cache.clear(function () {
      uni.showToast({
        title: useT('缓存清除成功'),
        duration: 2000
      });
      calculateCacheSize();
    });
  }
  // #endif
};

// 注销账号
const deregisterAccount = () => {
  uni.showModal({
    title: useT('注销账号'),
    content: `${useT('注销后无法恢复，请谨慎操作')}，${useT('确定要注销吗')}？`,
    cancelText: useT('取消'),
    confirmText: useT('确定'),
    confirmColor: '#ff4444',
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: useT('注销账号功能开发中'),
          icon: 'none'
        });
      }
    }
  });
};

// 退出登录
const logout = () => {
  uni.showModal({
    title: useT('退出登录'),
    content: `${useT('确定要退出登录吗')}？`,
    cancelText: useT('取消'),
    confirmText: useT('确定'),
    confirmColor: '#ff4444',
    success: (res) => {
      if (res.confirm) {
        userStore.logout();
        uni.showToast({
          title: useT('已退出登录'),
          icon: 'success'
        });
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/login/login'
          });
        }, 1500);
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.setting-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-top: 10rpx;

  // 菜单列表
  .menu-list {
    background-color: #ffffff;
    margin: 20rpx 30rpx 0;

    .menu-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 40rpx 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      position: relative;

      &:last-child {
        border-bottom: none;
      }

      .menu-text {
        font-size: 32rpx;
        color: #333333;
        font-weight: 500;
      }

      .cache-info,
      .version-info,
      .language-info {
        display: flex;
        align-items: center;

        .cache-size,
        .version-number,
        .current-language {
          font-size: 28rpx;
          color: #999999;
          margin-right: 20rpx;
        }
      }

      // 点击效果
      &:active {
        background-color: #f5f5f5;
      }
    }
  }

  // 退出登录区域
  .logout-section {
    padding: 60rpx 30rpx 40rpx;

    .logout-btn {
      background: #f44336;
      border-radius: 12rpx;
      padding: 24rpx 0;
      text-align: center;
      box-shadow: 0 4rpx 12rpx rgba(244, 67, 54, 0.3);

      .logout-text {
        color: #ffffff;
        font-size: 32rpx;
        font-weight: 600;
      }

      // 点击效果
      &:active {
        transform: translateY(2rpx);
        box-shadow: 0 2rpx 8rpx rgba(244, 67, 54, 0.3);
      }
    }
  }
}
</style>
